<template>
  <div class="app-container">
    <div class="header-bar">
      <el-button type="primary" class="mb-4" @click="handleAddReturnGoods">新增退货</el-button>
      <el-input
        placeholder="请输入退货/关联合同编号"
        style="width: 240px; float: right; margin-bottom: 10px;"
        v-model="query.keyword"
        @keyup.enter="handleSearch"
        clearable
      >
        <template #append>
          <el-button icon="Search" @click="handleSearch"></el-button>
        </template>
      </el-input>
    </div>
    <el-table :data="returnGoodsList" style="width: 100%" border>
      <el-table-column prop="returnNo" label="退货编号" align="left" :show-overflow-tooltip="true" />
      <el-table-column prop="contractHT" label="关联合同" align="left" :show-overflow-tooltip="true" />
      <el-table-column prop="contractNo" label="关联合同编号" align="left" :show-overflow-tooltip="true" />
      <el-table-column prop="logisticsNo" label="退货物流单号" align="left" :show-overflow-tooltip="true" />
      <el-table-column prop="customerPerson" label="客户名称" align="left" :show-overflow-tooltip="true" />
      <el-table-column prop="operator" label="操作人" align="left" :show-overflow-tooltip="true" />
      <el-table-column prop="returnTime" label="退货时间" align="left" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="left">
        <template #default="scope">
          <el-link type="primary" @click="handleView(scope.row)">查看</el-link>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 20px; justify-content: flex-end;"
      v-model:current-page="query.pageNum"
      v-model:page-size="query.pageSize"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增退货弹窗组件 -->
    <create-returngoods-step-form
      v-model:visible="createReturnGoodsVisible"
      :material-tree-data="materialTreeData"
      :contract-name-options="contractNameOptions"
      :requirement-options="requirementOptions"
      @close="handleCloseCreateReturnGoods"
      @complete="handleCreateReturnGoodsComplete"
    />
    
    <!-- 退货详情弹窗组件 -->
    <return-goods-info
      v-model="returnGoodsInfoVisible"
      :return-goods-data="selectedReturnGoodsData"
      @close="handleCloseReturnGoodsInfo"
    />
  </div>
</template>

<script setup name="returngoods">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
// 导入新增退货弹窗组件
import CreateReturngoodsStepForm from './createReturngoodsStepForm.vue'
// 导入退货详情弹窗组件
import ReturnGoodsInfo from './returnGoodsInfo.vue'
// 导入退货列表接口
import { queryReturnGoodsPage } from '@/api/stock'



// 查询参数
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: ''
})

// 数据总数
const total = ref(3) // 模拟数据总数

// 加载状态
const loading = ref(false)

// 新增退货弹窗显示状态
const createReturnGoodsVisible = ref(false)

// 退货详情弹窗显示状态
const returnGoodsInfoVisible = ref(false)

// 选中的退货数据
const selectedReturnGoodsData = ref({})

// 模拟数据（从出库管理页面复制并调整）
const originalData = [
  {
    returnNo: 'CPBH001',
    contractHT: '合同名称1',
    contractNo: 'HTBH001',
    logisticsNo: 'THWLDH001',
    operator: '张三(zhangsan)',
    customerPerson: '某某某公司',
    returnTime: '2025-04-05 17:38:03'
  },
  {
    returnNo: 'CPBH002',
    contractHT: '合同名称1',
    contractNo: 'HTBH001',
    logisticsNo: 'THWLDH002',
    operator: '张三(zhangsan)',
    customerPerson: '某某某公司',
    returnTime: '2025-04-05 17:38:03'
  },
  {
    returnNo: 'CPBH003',
    contractHT: '合同名称2',
    contractNo: 'HTBH002',
    logisticsNo: 'THWLDH003',
    operator: '张三(zhangsan)',
    customerPerson: '某某某公司2',
    returnTime: '2025-04-05 17:38:03'
  }
]

// 表格数据
const returnGoodsList = ref([])

// 物料树数据（参考出库管理页面）
const materialTreeData = ref([
  {
    id: 1,
    label: '卷帘门',
    value: 'rollingDoor',
    disabled: false
  },
  {
    id: 2,
    label: '防火门',
    value: 'fireDoor',
    disabled: false,
    children: [
      {
        id: 3,
        label: '二级分类',
        value: 'secondLevel',
        disabled: true,
        children: [
          {
            id: 4,
            label: '木质防火门——门框',
            value: 'doorframe',
            disabled: true
          },
          {
            id: 5,
            label: '木质防火门——门扇',
            value: 'doorleaf',
            disabled: true
          }
        ]
      }
    ]
  }
])

// 合同名称选项
const contractNameOptions = ref([
  { label: '合同名称11111', value: 'contract1' },
  { label: '和公司的合同1', value: 'contract2' },
  { label: '和公司的合同2', value: 'contract3' },
  { label: '和公司的合同3', value: 'contract4' }
])

// 需求选项（适配级联选择器格式）
const requirementOptions = ref([
  {
    id: 1,
    value: 'req1',
    label: '已出库需求1',
    children: [
      {
        id: 11,
        value: 'req1_order1',
        label: '加工单1'
      }
    ]
  },
  {
    id: 2,
    value: 'req2',
    label: '已出库需求2',
    children: [
      {
        id: 21,
        value: 'req2_order2',
        label: '加工单2'
      }
    ]
  },
  {
    id: 3,
    value: 'req3',
    label: '已出库需求3',
    children: [
      {
        id: 31,
        value: 'req3_order3',
        label: '加工单3'
      }
    ]
  }
])

// 获取退货列表
const getReturnGoodsList = async () => {
  loading.value = true
  queryReturnGoodsPage(query).then(res => {
    loading.value = false
    returnGoodsList.value = res.data?.list || [];
    total.value = res.data?.total || 0;
  }).catch(() => {
    returnGoodsList.value = [];
    loading.value = false
  });
}

// 搜索
function handleSearch() {
  query.pageNum = 1
  getReturnGoodsList()
}

// 重置搜索
function handleReset() {
  query.keyword = ''
  query.pageNum = 1
  getReturnGoodsList()
}

// 新增退货
function handleAddReturnGoods() {
  createReturnGoodsVisible.value = true
}

// 查看退货详情
function handleView(row) {
  // 准备详情页需要的数据
  selectedReturnGoodsData.value = {
    returnNumber: row.returnNo,
    contractName: row.contractHT,
    contractNumber: row.contractNo,
    customerName: row.customerPerson,
    salesPerson: row.operator,
    materialName: '防火门', // 模拟数据
    productList: [
      {
        productCode: 'CPBH001',
        materialContent: '防火门/二级分类/木质门框',
        demand: '需求1',
        productionOrder: 'SCJHD001'
      },
      {
        productCode: 'CPBH002',
        materialContent: '防火门/二级分类/木质门框',
        demand: '需求1',
        productionOrder: 'SCJHD001'
      },
      {
        productCode: 'CPBH003',
        materialContent: '防火门/二级分类/木质门扇',
        demand: '需求2',
        productionOrder: 'SCJHD004'
      }
    ],
    logisticsNumber: row.logisticsNo,
    returnAddress: '湖北省武汉市汉阳区xxxxx', // 模拟数据
    contactPerson: row.operator, // 模拟数据
    contactPhone: '15000000000', // 模拟数据
    returnReason: '产品型号不对', // 模拟数据
    operator: row.operator,
    returnTime: row.returnTime
  }
  // 显示详情弹窗
  returnGoodsInfoVisible.value = true
}

// 关闭退货详情弹窗
function handleCloseReturnGoodsInfo() {
  returnGoodsInfoVisible.value = false
  selectedReturnGoodsData.value = {}
}

// 关闭新增退货弹窗
function handleCloseCreateReturnGoods() {
  console.log('关闭新增退货弹窗')
}

// 新增退货完成
function handleCreateReturnGoodsComplete(formData) {
  console.log('新增退货完成，表单数据:', formData)
  ElMessage.success('新增退货成功')
  // 重新获取列表数据
  getReturnGoodsList()
}

// 分页大小改变
function handleSizeChange(val) {
  query.pageSize = val
  query.pageNum = 1
  getReturnGoodsList()
}

// 当前页码改变
function handleCurrentChange(val) {
  query.pageNum = val
  getReturnGoodsList()
}

// 初始化
onMounted(() => {
  getReturnGoodsList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  box-sizing: border-box;
}

.header-bar {
  margin-bottom: 10px;
  overflow: hidden;
}

.ml10 {
  margin-left: 15px;
}

:deep(.el-pagination) {
  display: flex;
  justify-content: flex-end;
  flex-wrap: wrap;
}
</style>
